import { Regions } from '@/API/api';

export default {
    namespaced: true,
    state: {
        regionsList: [],
    },
    getters: {
        
    },
    mutations: {
        getRegionsList(state:any, payload = []) {
            const result:Array<object> = [];
            const map:any = {};
            const setChildren = (list:any) => {
                for (let item of list) {
                    if (map[item.region_id]) {
                        item.children = map[item.region_id];
                        setChildren(item.children);
                    }
                }
            };
            payload.forEach((item:any) => {
                if (item.parent_id !== '0') {
                    if (!map[item.parent_id]) {
                        map[item.parent_id] = [];
                    }
                    map[item.parent_id].push(item);
                } else {
                    item.children = [];
                    result.push(item);
                }
            });
            setChildren(result);
            const [ item ]:any = result
            state.regionsList = item.children;
        }
    },
    actions: {
        async GET_REGIONS_LIST({ commit, state }:any) {
            const { data: { payload: { code, list } } } = await Regions('/all-region').stream({
                method: 'get',
                params: {
                    asdf: 12,
                    qwe: '123',
                },
            })
            if(code === 200) {
                commit('getRegionsList', list)
                return list;
            }
        }
    },
};